package data

import (
	"errors"
	"manage/app/course/internal/biz"
	"strings"
	"time"

	"github.com/Fromsko/gouitls/auth"
	"github.com/Fromsko/gouitls/logs"
	"github.com/go-kratos/kratos/v2/log"
	"gorm.io/gorm"
)

var echo = logs.InitLogger()

type courseRepo struct {
	data *Data
	log  *log.Helper
}

func NewcourseRepo(data *Data, logger log.Logger) biz.CourseRepo {
	c := &courseRepo{
		data: data,
		log:  log.NewHelper(logger),
	}
	c.Setup()
	return c
}

// Setup 初始化
func (u *courseRepo) Setup() {

	func(db *gorm.DB) {
		if db.Migrator().HasTable(biz.Course{}) {
			echo.Warn("课程表已存在, 跳过创建。")
			return
		}

		if err := db.AutoMigrate(biz.Course{}); err != nil {
			echo.Errorf("创建表失败：%v", err)
		}

		echo.Info("课程表创建完成")
	}(u.data.Mysql)

}

func CheckCourse(db *gorm.DB, courseID string) (*biz.Course, error) {

	courseInfo := &biz.Course{}

	err := db.Where("course_id = ?", courseID).First(courseInfo)
	if err.Error == gorm.ErrRecordNotFound {
		return nil, errors.New("课程不存在")
	}
	return courseInfo, nil
}

// TODO: 创建课程
func (repo *courseRepo) CreateCourse(req *biz.CreateCourseRequest) (*biz.CreateCourseResponse, error) {

	t := time.Now()
	newCourse := biz.Course{
		CourseName:        req.CourseName,
		CourseDescription: req.CourseDescription,
		CreatedAt:         t,
		UpdatedAt:         t,
		CourseID:          strings.Split(auth.GenUUID(req.CourseName), "-")[4],
	}
	reply := &biz.CreateCourseResponse{
		Message:  "课程创建成功",
		CourseID: newCourse.CourseID,
	}

	_, err := CheckCourse(repo.data.Mysql, newCourse.CourseID)
	if err == nil {
		err = errors.New("课程已存在")
		reply.Message = err.Error()
		return nil, err
	}

	result := repo.data.Mysql.Create(&newCourse)
	if result.Error != nil {
		echo.Errorf("Create err: %s", err.Error())
		return nil, result.Error
	}
	return reply, nil
}

// TODO: 删除课程
func (repo *courseRepo) DeleteCourse(courseID string) error {

	_, err := CheckCourse(repo.data.Mysql, courseID)
	if err != nil {
		return err
	}

	result := repo.data.Mysql.Where("course_id = ?", courseID).Delete(&biz.Course{})
	if result.Error != nil {
		echo.Errorf("Delete err: %s", err.Error())
		return result.Error
	}
	return nil
}

// TODO: 更新课程
func (repo *courseRepo) UpdateCourse(request *biz.CreateCourseRequest, courseID string) error {

	resp, err := CheckCourse(repo.data.Mysql, courseID)
	if err != nil {
		return err
	}

	resp.UpdatedAt = time.Now()
	resp.CourseName = request.CourseName
	resp.CourseDescription = request.CourseDescription

	result := repo.data.Mysql.Where("course_id = ?", courseID).Save(&resp)
	if result.Error != nil {
		echo.Errorf("Update err: %s", err.Error())
		return result.Error
	}
	return nil
}

// TODO: 查询课程
func (repo *courseRepo) GetCourseInfo(courseID string) (*biz.GetCourseResponse, error) {

	resp, err := CheckCourse(repo.data.Mysql, courseID)
	if err != nil {
		return nil, err
	}
	return &biz.GetCourseResponse{
		CourseID:          resp.CourseID,
		CourseName:        resp.CourseName,
		CourseDescription: resp.CourseDescription,
	}, nil
}
